package com.hspedu.hspspringmvc.context;

import com.hspedu.hspspringmvc.annotation.Controller;
import com.hspedu.hspspringmvc.xml.XMLPaser;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * packageName com.hspedu.hspspringmvc.context
 *
 * @author 你的名字
 * @version JDK 8
 * @className HspWebApplicationContext (此处以class为例)
 * @date 2025/2/12
 * @description TODO
 */
public class HspWebApplicationContext {
    private ArrayList<String> classFullPathList = new ArrayList<>();
    public ConcurrentHashMap<String, Object> ioc = new ConcurrentHashMap<>();
    private String contextConfigLocation ="";
    public HspWebApplicationContext(){}

    public HspWebApplicationContext(String contextConfigLocation){
        this.contextConfigLocation = contextConfigLocation;
    }


    public void init(){
        String basePackage
                = XMLPaser.getbasePackage(contextConfigLocation.split(":")[1]);
        String[] packages = basePackage.split(",");
        if (packages.length > 0){
            for (String aPackage : packages) {
                scanPackage(aPackage);
            }
        }
        //测试
        System.out.println("扫描后的 classFullPathList= " + classFullPathList);
        executeInstance();
        System.out.println("ioc= " + ioc);

    }

    public void scanPackage(String packageName){
        URL resource = this.getClass().getClassLoader().getResource("/" + packageName.replaceAll("\\.", "/"));
        System.out.println("URL:"+resource);
        String  path = resource.getFile();
        File dir = new File(path);
        for (File file : dir.listFiles()){
            if (file.isDirectory()){
                scanPackage(packageName + "." + file.getName());
            }else {
                if (file.getName().endsWith(".class")){
                    String className = packageName + "." + file.getName().replace(".class", "");
                    classFullPathList.add(className);
                }
            }
        }
        System.out.println(classFullPathList);

    }

    public void executeInstance(){
        if (classFullPathList.size() > 0){
            try {
                for (String classFullPath : classFullPathList) {
                    Class<?> aClass = Class.forName(classFullPath);
                    if (aClass.isAnnotationPresent(Controller.class)){
                        Object instance = aClass.newInstance();
                     String aClassName =   aClass.getSimpleName().substring(0, 1).toLowerCase()
                             + aClass.getSimpleName().substring(1);
                     ioc.put(aClassName, instance);

                    }

                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


}
